import {
  ArrowLeftOutlined,
  ArrowRightOutlined,
  EditOutlined,
  EyeOutlined,
  PlusCircleOutlined,
} from '@ant-design/icons';
import {
  ModalForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { useEditor, useEditorReturnType } from '@craftjs/core';
import { request, useRequest } from '@umijs/max';
import {
  Button,
  Col,
  Dropdown,
  Flex,
  message,
  Row,
  type MenuProps,
} from 'antd';
import React, { useRef } from 'react';

const AddRemoteModule: React.FC<{
  query: useEditorReturnType['query'];
  add: useEditorReturnType['actions']['addNodeTree'];
}> = ({ query, add }) => {
  const items: MenuProps['items'] = [
    {
      key: 'PLUS',
      label: 'Remote Add',
      onClick() {
        const node = query.parseReactElement(<div>6666</div>).toNodeTree();

        add(node, 'ROOT');
      },
    },
  ];

  return (
    <Dropdown menu={{ items }}>
      <Button shape="circle" icon={<PlusCircleOutlined />}></Button>
    </Dropdown>
  );
};

export const Tools: React.FC = () => {
  const {
    preview,
    actions: { setOptions, history, addNodeTree },
    query,
  } = useEditor((state) => ({
    preview: !state.options.enabled,
  }));

  const formRef = useRef<ProFormInstance>();

  const { run: save } = useRequest(
    (data) => {
      return request('/api/kits', {
        method: 'POST',
        data: {
          ...data,
          type: 'Kit',
        },
      });
    },
    {
      manual: true,
    },
  );

  return (
    <Row
      style={{ padding: '10px 0' }}
      justify={preview ? 'center' : 'space-between'}
      align={'middle'}
    >
      {!preview && (
        <Col>
          <Button onClick={() => history.undo()}>
            <ArrowLeftOutlined />
          </Button>
          &nbsp; &nbsp; &nbsp;
          <Button onClick={() => history.redo()}>
            <ArrowRightOutlined />
          </Button>
        </Col>
      )}
      <Col>
        <Flex gap={'small'}>
          <Button
            shape="circle"
            icon={preview ? <EditOutlined /> : <EyeOutlined />}
            onClick={() =>
              setOptions((options) => (options.enabled = !options.enabled))
            }
          />
          <AddRemoteModule query={query} add={addNodeTree} />
        </Flex>
      </Col>
      {!preview && (
        <Col>
          <ModalForm
            formRef={formRef}
            title="保存"
            trigger={<Button type="primary">Submit</Button>}
            onFinish={async (values) => {
              await save({
                name: values.name,
                description: values.description,
                content: query.serialize(),
                imageUrl: values.imageUrl?.length
                  ? values.imageUrl[0]?.thumbUrl
                  : '',
                tag: values.tag,
              });
              message.success('保存成功');
              formRef.current?.resetFields();
              return true;
            }}
          >
            <ProFormText
              name={'name'}
              label="名称"
              rules={[
                {
                  required: true,
                  message: '请输入模板名称',
                },
              ]}
              placeholder={'请输入模板名称'}
            />
            <ProFormSelect
              fieldProps={{
                mode: 'multiple',
              }}
              label={'标签'}
              name={'tag'}
              request={async () => {
                const res = await request('/api/labels', {
                  method: 'GET',
                  params: {
                    type: 'Kit',
                  },
                });

                return res?.data?.rows.map((item: any) => ({
                  label: item.label,
                  value: item.name,
                }));
              }}
              rules={[
                {
                  required: true,
                  message: '请选择标签',
                },
              ]}
              placeholder={'请选择标签'}
            />
            <ProFormUploadButton
              max={1}
              name={'imageUrl'}
              label="图片"
              rules={[
                {
                  required: true,
                  message: '请上传图片',
                },
              ]}
              fieldProps={{
                beforeUpload(file) {
                  return new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);

                    reader.onload = () => {
                      if (!reader.result) return;
                      formRef.current?.setFieldsValue({
                        imageUrl: reader.result,
                      });
                      resolve(reader.result as string);
                    };
                  });
                },
              }}
            />
            <ProFormText
              name={'description'}
              label="描述"
              rules={[
                {
                  required: true,
                  message: '请选择套件输入描述',
                },
              ]}
              placeholder={'请选择套件输入描述'}
            />
          </ModalForm>
        </Col>
      )}
    </Row>
  );
};
